package com.jn.exam.easypoi.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.exam.CloneUtils;
import com.jn.exam.HTMLUtil;
import com.jn.exam.MD5Util;
import com.jn.exam.R;
import com.jn.exam.easypoi.entity.*;
import com.jn.exam.easypoi.service.*;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;

/**
 * <p>
 * 总题库 前端控制器
 * </p>
 *
 * @author 江南大学1033190417
 * @since 2022-01-22
 */
@RestController
@RequestMapping("/easypoi")
@Api(description = "操作报表")
public class EasyPoiController {
    @Autowired
    private QuestionService questionService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private PersonalQuestionService personalQuestionService;


    @ApiOperation("主管导入Excel题目到总题库")
    @PostMapping("getQuestionFromExcelAndStorage")
    @Transactional(rollbackFor = Exception.class)
    public R getQuestionFromExcelAndStorage(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);//表格标题行数,默认0
        params.setHeadRows(1);//表头行数，默认1
        List<Question> questions = ExcelImportUtil.importExcel(file.getInputStream(), Question.class, params);
        List<Future<Boolean>> futures = new ArrayList<>();
        for (Question question : questions) {
            Future<Boolean> future = questionService.saveQuestionFromExcel(question);
            futures.add(future);
        }
        for (Future<Boolean> f : futures) {
            Boolean b = f.get();
            if (!b) {
                return R.error().message("导入失败");
            }
        }
        return R.ok().message("导入成功");
    }


    @ApiOperation("老师导入Excel题目到个人题库")
    @PostMapping(value = "getPersonalQuestionFromExcelAndStorage")
    @Transactional(rollbackFor = Exception.class)
    public R getPersonalQuestionFromExcelAndStorage(MultipartFile file, String[] personalQuestionStoreIds) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);//表格标题行数,默认0
        params.setHeadRows(1);//表头行数，默认1
        List<PersonalQuestion> personalQuestions = ExcelImportUtil.importExcel(file.getInputStream(), PersonalQuestion.class, params);
        List<Future<Boolean>> futures = new ArrayList<>();
        for (PersonalQuestion question : personalQuestions) {
            for (String personalQuestionStoreId : personalQuestionStoreIds) {
                PersonalQuestion personalQuestion = CloneUtils.clone(question);
                String storeId=personalQuestionStoreId;
                Future<Boolean> future = personalQuestionService.savePersonalQuestionFromExcel(personalQuestion, storeId);
                futures.add(future);
            }
        }
        for (Future<Boolean> f : futures) {
            Boolean b = f.get();
            if (!b) {
                return R.error().message("导入失败");
            }
        }
        return R.ok().message("导入成功");
    }


    @ApiOperation("从Excel读取学生信息导入数据库")
    @PostMapping("getStudentFromExcelAndStorage")
    @Transactional(rollbackFor = Exception.class)
    public R getStudentFromExcelAndStorage(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);//表格标题行数,默认0
        params.setHeadRows(1);//表头行数，默认1
        List<Student> students = ExcelImportUtil.importExcel(file.getInputStream(), Student.class, params);
        for (Student student : students) {
            student.setPassword(MD5Util.getMD5("123456"));
            String faceGroupId = studentService.getOneFaceGroup();
            student.setFaceGroupId(faceGroupId);
        }
        boolean saveBatch = studentService.saveBatch(students);
        if (saveBatch) {
            return R.ok().message("导入成功");
        }
        return R.error().message("导入失败");
    }

    @ApiOperation("从Excel读取老师信息导入数据库")
    @PostMapping("getTeacherFromExcelAndStorage")
    @Transactional(rollbackFor = Exception.class)
    public R getTeacherFromExcelAndStorage(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<Teacher> teachers = ExcelImportUtil.importExcel(file.getInputStream(), Teacher.class, params);
        for (Teacher teacher : teachers) {
            teacher.setPassword(MD5Util.getMD5("123456"));
        }
        boolean b = teacherService.saveBatch(teachers);
        if (b) {
            return R.ok().message("导入成功");
        }
        return R.error().message("导入失败");
    }

    @ApiOperation("导出学生数据到Excel")
    @GetMapping("getStudentToExcel")
    public R getStudentToExcel() throws Exception {
        List<Student> students = studentService.list(null);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("学生库信息表", "学生"), Student.class, students);
        FileOutputStream outputStream = new FileOutputStream("D:\\桌面\\模板\\students.xls");
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
        return R.ok().message("导出成功");
    }

    @ApiOperation("导出老师到Excel")
    @GetMapping("getTeacherToExcel")
    public R getTeacherToExcel() throws Exception {
        List<Teacher> teachers = teacherService.list(null);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("老师信息表", "老师"), Teacher.class, teachers);
        FileOutputStream outputStream = new FileOutputStream("D:\\桌面\\模板\\teachers.xls");
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
        return R.ok().message("导出成功");
    }

    @ApiOperation("导出总题库到Excel")
    @GetMapping("getQuestionToExcel")
    public R getQuestionToExcel() throws Exception {
        List<Question> questions = questionService.list(null);
        for (Question question : questions) {
            String name = question.getName();
            name = HTMLUtil.getHtmlText(name);
            question.setName(name);
            String answer = question.getAnswer();
            answer = HTMLUtil.getHtmlText(answer);
            question.setAnswer(answer);
        }
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("总题库信息表", "题目"), Question.class, questions);
        FileOutputStream outputStream = new FileOutputStream("D:\\桌面\\模板\\questions.xls");
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
        return R.ok().message("导出成功");
    }

    @ApiOperation("导出个人题库试题")
    @GetMapping("getPersonalQuestionToExcel")
    public R getPersonalQuestionToExcel(String[] personalQuestionStoreIds){
        QueryWrapper<PersonalQuestion> wrapper=new QueryWrapper<>();
        wrapper.in("store_id", personalQuestionStoreIds);
        List<PersonalQuestion> personalQuestions = personalQuestionService.list(wrapper);
        return R.ok().data("personalQuestions",personalQuestions);
    }
}

